import Vue from 'vue'
import Router from 'vue-router'

// import Home from '@/views/home'
// import Operator from '@/views/system/operator'
// import Role from '@/views/system/Role'
// import Permission from '@/views/system/Permission'
// import Menu from '@/views/system/Menu'

// var templatePath = '@/views/'

Vue.use(Router)

function asyncView (template) {
  return require(`@/views${template}`).default
}

var router = new Router({
  routes: [
    { path: '/login', component: asyncView('/Login.vue'), meta: { auth: false } }
  ]
})

// 登录检测
router.beforeEach((to, from, next) => {
  // router.app.$bus.$emit('hideMsg')
  console.log('path', to.path, from.path)

  var token = router.app.$cookie.get('userToken')
  if (to.matched.some(m => m.meta.auth) && !token) {
    router.push('/login?path=' + to.path)
  }
  next()
})

// 路由跳转 不必区分 路由path 和url
router.go = function (url) {
  if (/^javas/.test(url) || !url) return
  const useRouter = typeof url === 'object' || (router && typeof url === 'string' && !/http/.test(url))
  if (useRouter) {
    if (url === '/') router.push('/home')
    else router.push(url)
  } else {
    window.location.href = url
  }
}

// 路由跳转 不必区分 路由path 和url
router.updateRouters = function (menus) {
  // var menus = app.$operator.menuList
  for (var i in menus) {
    var menu = menus[i]
    var routerItems = []
    if (!menu.hidden) {
      // 路由设置
      var routerItem = {
        path: menu.path,
        component: asyncView(menu.template),
        name: menu.name,
        icon: menu.icon,
        meta: { auth: false },
        children: []
      }
      // 子路由 (暂不支持三层结构)
      if (menu.hasOwnProperty('submenu')) {
        for (var j in menu.submenu) {
          var submenu = menu.submenu[j]
          routerItem.children.push({
            path: submenu.path,
            component: asyncView(submenu.template),
            name: submenu.name,
            icon: submenu.icon,
            meta: { auth: false }
          })
        }
      }
      routerItems.push(routerItem)
      router.addRoutes(routerItems)
    }
  }
}

export default router
